﻿using System;
using System.Collections.Concurrent;
using System.Configuration;
using System.Threading;
using System.Threading.Tasks;
using Out.TaskRunner.RmqWorkers;
using Quartz;
using Quartz.Impl;

namespace Out.TaskRunner
{
    class Program
    {
        static void Main(string[] args)
        {
            // 注册微信
            SenparcWeixinConfig.Register();

            // 注册 MQ 消费 任务
            Task task;
            var tasks = new ConcurrentBag<Task>();
            var cts = new CancellationTokenSource();
            var ct = cts.Token;

            // 解锁号源
            task = Task.Factory.StartNew(() => new OrderUnlockingWorker().Start(ct), ct, TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
            tasks.Add(task);
            // 取消预约
            //task = Task.Factory.StartNew(() => new OrderUnapptingWorker().Start(ct), ct, TaskCreationOptions.LongRunning,
            //    TaskScheduler.Default);
            //tasks.Add(task);
            // 支付超时
            task = Task.Factory.StartNew(() => new OrderPayingTimeoutWorker().Start(ct), ct, TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
            tasks.Add(task);
            // 执行订单（院内取号，缴费等）
            task = Task.Factory.StartNew(() => new OrderPickupingWorker().Start(ct), ct, TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
            tasks.Add(task);
            // 订单执行状态检查
            task = Task.Factory.StartNew(() => new OrderPickupingChkWorker().Start(ct), ct, TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
            tasks.Add(task);
            // 订单执行失败退费
            task = Task.Factory.StartNew(() => new OrderRefundingPickupFailedWorker().Start(ct), ct, TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
            tasks.Add(task);
            // 退号
            task = Task.Factory.StartNew(() => new OrderUnpickupingWorker().Start(ct), ct, TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
            tasks.Add(task);
            // 退号状态检查
            task = Task.Factory.StartNew(() => new OrderUnpickupingChkWork().Start(ct), ct, TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
            tasks.Add(task);
            // 退号退费
            task = Task.Factory.StartNew(() => new OrderRefundingUnpickupSucceedWorker().Start(ct), ct, TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
            tasks.Add(task);
            // 用户通知消息
            task = Task.Factory.StartNew(() => new UserMessageWorker().Start(ct), ct, TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
            tasks.Add(task);


            IScheduler sched = null;
            if (ConfigurationManager.AppSettings["StartQuartz"] == "true")
            {
                //启动 Quartz
                ISchedulerFactory sf = new StdSchedulerFactory();
                sched = sf.GetScheduler();

                sched.Start();
            }

            //Test();
            
            Console.WriteLine("Out.TaskRunner 服务程序已启动！");
            Console.WriteLine("输入 exit 来终止程序.");
            while (true)
            {
                if (Console.ReadLine() == "exit")
                {
                    cts.Cancel();

                    Task.WaitAll(tasks.ToArray());

                    sched?.Shutdown(true);
                    break;
                }
            }
        }

        //private static void Test()
        //{
        //    using (var ctx = new HzfyWeiXinEntities())
        //    {
        //        var orders = ctx.ApptOrders.Where(
        //            x => x.OpenId == "oxKlnuJnTV6TgnZ7hqzG_0-spINI" &&
        //            SqlFunctions.DateDiff("day", x.CreateTime, DateTime.Today) == 0)
        //            .ToList();

        //        foreach (var apptOrder in orders)
        //        {
        //            Console.WriteLine("开始取消预约，OrderId:{0}", apptOrder.Id);

        //            var unApptRequest = new CancelAppointRequest();
        //            unApptRequest.OrderId = apptOrder.OrderNo;
        //            CancelAppointResponse unApptResponse;
        //            try
        //            {
        //                var httpClient = InHttpClient.GetClient();
        //                var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/CancelAppoint", unApptRequest).Result;
        //                responseMsg.EnsureSuccessStatusCode();
        //                unApptResponse = responseMsg.Content.ReadAsAsync<CancelAppointResponse>().Result;
        //            }
        //            catch (Exception ex)
        //            {
        //                Console.WriteLine("调用院内取消预约Api出错,OrderId:{0}, 信息：{1}", apptOrder.Id,
        //                    JsonConvert.SerializeObject(ex));

        //                continue;
        //            }

        //            if (unApptResponse.ResultCode == "0")
        //            {
        //                Console.WriteLine("取消预约成功，OrderId:{0}", apptOrder.Id);
        //            }
        //            else
        //            {
        //                Console.WriteLine("取消预约失败，开始解锁，OrderId:{0},原因:{1}", apptOrder.Id, unApptResponse.ResultDesc);

        //                //执行取消锁号操作
        //                var unlockRequest = new ExeUnLockSourceRequest();
        //                unlockRequest.OrderId = apptOrder.OrderNo;

        //                ExeUnLockSourceResponse unlockResponse;
        //                try
        //                {
        //                    var httpClient = InHttpClient.GetClient();
        //                    var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/ExeUnLockSource", unlockRequest).Result;
        //                    responseMsg.EnsureSuccessStatusCode();
        //                    unlockResponse = responseMsg.Content.ReadAsAsync<ExeUnLockSourceResponse>().Result;
        //                }
        //                catch (Exception ex)
        //                {
        //                    Console.WriteLine("调用院内取消锁号Api出错,OrderId:{0},信息：{1}", apptOrder.Id,
        //                        JsonConvert.SerializeObject(ex));

        //                    continue;
        //                }

        //                if (unlockResponse.ResultCode == "0")
        //                {
        //                    Console.WriteLine("解锁成功，OrderId:{0}", apptOrder.Id);
        //                }
        //                else
        //                {
        //                    Console.WriteLine("解锁失败，OrderId:{0}，原因:{1}", apptOrder.Id, unlockResponse.ResultDesc);
        //                }
        //            }
        //        }
        //    }
        //}
    }
}
